/**
 * Copyright (c) 2014-2016 www.nryuncang.com. All Rights Reserved.
 */
package com.topisv.tms.service.print.impl;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.shiro.SecurityUtils;
import org.slf4j.LoggerFactory;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.topisv.tms.entity.Consignor;
import com.topisv.tms.entity.CustomerAreaGroup;
import com.topisv.tms.entity.Customers;
import com.topisv.tms.entity.EcCorePrintRegion;
import com.topisv.tms.entity.EdiGoodsSku;
import com.topisv.tms.entity.EdiOrder;
import com.topisv.tms.entity.EdiOrderItem;
import com.topisv.tms.entity.ExpressStyle;
import com.topisv.tms.entity.User;
import com.topisv.tms.entity.WarehouseAddress;
import com.topisv.tms.entity.YTOShortAddress;
import com.topisv.tms.entity.log.OrderLog;
import com.topisv.tms.entity.work.WorkLog;
import com.topisv.tms.entity.work.WorkOrder;
import com.topisv.tms.entity.work.WorkTask;
import com.topisv.tms.repository.CustomersDao;
import com.topisv.tms.repository.UserDao;
import com.topisv.tms.repository.YTOShortAddressDao;
import com.topisv.tms.repository.log.OrderLogDao;
import com.topisv.tms.repository.work.WorkLogDao;
import com.topisv.tms.repository.work.WorkOrderDao;
import com.topisv.tms.repository.work.WorkTaskDao;
import com.topisv.tms.service.ConsignorService;
import com.topisv.tms.service.CustomerAreaGroupService;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.EcCorePrintRegionService;
import com.topisv.tms.service.EdiGoodsSkuService;
import com.topisv.tms.service.EdiOrderItemService;
import com.topisv.tms.service.ExpressStyleService;
import com.topisv.tms.service.WarehouseAddressService;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.service.print.IPrintService;
import com.topisv.tms.service.vo.CNPrinterModel;
import com.topisv.tms.service.vo.CNPrinterStyleType;
import com.topisv.tms.service.vo.PackItems;
import com.topisv.tms.service.vo.PrinterStyleType;
import com.topisv.tms.service.work.WorkOrderService;
import com.topisv.tms.service.work.WorkTaskService;
import com.topisv.tms.slf4j.MarkerConstant;
import com.topisv.tms.utils.FileOperation;
import com.topisv.tms.utils.PrintModelUtil;
import com.topisv.tms.utils.TimeUtil;
import com.topisv.tms.utils.enums.StatusEnums;
import com.topisv.tms.utils.print.PackFormUtil;

import net.sf.json.JSONObject;

/**
 * 打印服务抽象实现
 *
 * @author <a href=mailto:zhangweize@nryuncang.com>zhangweize</a>
 * @version 0.0.16
 */
@Component
public abstract class AbstractPrintService implements IPrintService {

	private static final org.slf4j.Logger logger = LoggerFactory.getLogger(AbstractPrintService.class);

	@Autowired
	private ConsignorService consignorService;

	@Autowired
	private CustomersService customersService;

	@Autowired
	private ExpressStyleService expressStyleService;
	@Autowired
	private EdiOrderItemService ediOrderItemService;
	@Autowired
	private EdiGoodsSkuService ediGoodsskuService;
	@Autowired
	private WarehouseAddressService warehouseAddressService;
	@Autowired
	private WorkTaskService workTaskService;
	@Autowired
	private WorkOrderService workOrderService;
	@Autowired
	private EcCorePrintRegionService ecCorePrintRegionService;
	@Autowired
	private YTOShortAddressDao ytoShortAddressDao;

	@Autowired
	private CustomerAreaGroupService customerAreaGroupService;
	@Autowired
	private WorkOrderDao workOrderDao;
	@Autowired
	private OrderLogDao orderLogDao;
	@Autowired
	private WorkLogDao workLogDao;
	@Autowired
	private UserDao userDao;
	@Autowired
	private CustomersDao customersDao;
	@Autowired
	private WorkTaskDao workTaskDao;

	@Override
	public List<? extends PrinterStyleType> print(Long templateId, String taskCode, List<String> orderNoList) throws Exception {
	    long t1 = System.currentTimeMillis();
	    
		// 第一步：取打印的快递模板
		ExpressStyle template = getExpressStyle(templateId);
		long t2 = System.currentTimeMillis();

		// 第二步：取运单号
		List<EdiOrder> ediOrderList = doGetExpressNo(orderNoList, template, taskCode);
		long t3 = System.currentTimeMillis();

		// 第三步：渲染数据到模板
		List<PrinterStyleType> printerStyleList = getPrinterStyleTypes(ediOrderList, taskCode, template);
		long t4 = System.currentTimeMillis();

		// 第四步：更新task workorder 打印状态
		((AbstractPrintService) AopContext.currentProxy()).update(ediOrderList, taskCode, template);
		long t5 = System.currentTimeMillis();
		
		logger.info(MarkerConstant.MONITOR_MARKE, "打印模块. 快递公司:{}, taskCode:{}, 订单数量:{}. 总耗时:{}ms = {} + {} + {} + {}. (取打印模板+取运单号+渲染数据+更新状态)",
		    template.getLogisticsCompany().getCompanyCode(), taskCode, ediOrderList.size(), t5 - t1, t2 - t1, t3 - t2, t4 - t3, t5 - t4);

		// 返回渲染后的模板
		return printerStyleList;
	}

	/**
	 * 取打印快递模板
	 *
	 * @param expressId
	 * @return [参数说明]
	 * @author <a href=mailto:zhangweize@nryuncang.com>zhangweize</a>
	 * @version 0.0.16
	 */
	public ExpressStyle getExpressStyle(Long expressId) {
		return expressStyleService.findOne(expressId);
	}

	/**
	 * 获取运单号，由于各家不一，由子类实现
	 *
	 * @param orderNoList
	 * @return [参数说明]
	 * @author <a href=mailto:zhangweize@nryuncang.com>zhangweize</a>
	 * @version 0.0.16
	 */
	public abstract List<EdiOrder> doGetExpressNo(List<String> orderNoList, ExpressStyle template, String taskCode) throws Exception;

	/**
	 * 获取打印样式内容列表
	 *
	 * @param orderNoList
	 *            订单号列表
	 * @param taskCode
	 *            任务号
	 * @param template
	 *            快递模板
	 * @return 渲染数据后的打印样式列表
	 * @author <a href=mailto:zhangweize@nryuncang.com>zhangweize</a>
	 * @version 0.0.16
	 */
	public List<PrinterStyleType> getPrinterStyleTypes(List<EdiOrder> ediOrderList, String taskCode, ExpressStyle template) {
		ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();

		List<PrinterStyleType> pstList = new ArrayList<>(ediOrderList.size());
		for (EdiOrder ediOrder : ediOrderList) {
			// 取打印的数据内容
			CNPrinterModel pm = getExpressStyleModel(ediOrder, user, template);
			// 渲染
			PrinterStyleType pst = getPrinterStyleType(pm, template);

			pstList.add(pst);
		}

		return pstList;
	}

	/**
	 * HTTP Post请求
	 * 
	 *
	 * @param url
	 *            请求地址
	 * @param parameters
	 *            参数
	 * @return
	 * @throws Exception
	 *             [参数说明]
	 * @author <a href=mailto:zhangweize@nryuncang.com>zhangweize</a>
	 * @version 1.0.0
	 */
	public String requestExpressNo(String url, List<NameValuePair> parameters) throws Exception {

		StringBuffer sb = new StringBuffer();
		HttpClient client = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(url);
		httpPost.setEntity(new UrlEncodedFormEntity(parameters, Charset.forName("UTF-8")));

		HttpResponse httpResponse = client.execute(httpPost);
		BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), Charset.forName("UTF-8")));
		String content = null;
		while ((content = reader.readLine()) != null) {
			sb.append(content);
		}
		return sb.toString();
	}

	/**
	 * 更新workorder task 打印状态
	 *
	 * @param orderNoList
	 * @param taskCode
	 * @param expressId
	 *            [参数说明]
	 * @author <a href=mailto:zhangweize@nryuncang.com>zhangweize</a>
	 * @version 1.0.0
	 */
	@Transactional(readOnly = false, rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
	public void update(List<EdiOrder> ediOrderList, String taskCode, ExpressStyle template) {

		// 查询当前登录用户
		ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		User curUser = userDao.findOne(user.id);

		String logisticsCompanyCode = template.getLogisticsCompany().getCompanyCode();
		for (EdiOrder ediOrder : ediOrderList) {
			String mailNo = ediOrder.getMailNo();
//			WorkOrder workOrder = workOrderService.loadByAnyOrderno(ediOrder.getOrdeno());
			// if (!"1".equals(template.getCainiaoFlg()) &&
			// (TTKDEX.equals(logisticsCompanyCode) ||
			// STO.equals(logisticsCompanyCode))) {
			// LogisticsMailNo logisticsMailNo =
			// logisticsMailNoDao.findByMailNo(mailNo);
			// if (logisticsMailNo != null &&
			// !"finish".equals(logisticsMailNo.getStatus()) &&
			// logisticsMailNo.getCompanyCode().equals(logisticsCompanyCode)) {
			// logisticsMailNo.setStatus("finish");
			// logisticsMailNoDao.save(logisticsMailNo);
			// }
			// }

			// 修改作业订单
//			workOrder.setPrintStatus("printed");
//			workOrder.setExpressList(workOrder.getExpressList() == null ? mailNo : (workOrder.getExpressList() + ":" + mailNo));
//			workOrder.setExpressCompany(logisticsCompanyCode);
//			workOrder.setEbillNo(mailNo);
//			workOrder.setBillType(StatusEnums.WAYBILL_TYPE_EBILL.getStatus());
//			workOrder.setPrintFlag(workOrder.getPrintFlag() + 1);
//			workOrderDao.save(workOrder);
			
			/** begin modify 20161018 bug:515 */
			Long workOrderId = workOrderDao.loadIdByAnyOrderno(ediOrder.getOrdeno());
			int cnt = workOrderDao.updateStatusForPrint("printed", mailNo, logisticsCompanyCode, mailNo, StatusEnums.WAYBILL_TYPE_EBILL.getStatus(), 1, workOrderId);
			if (cnt == 0l) {
			    throw new RuntimeException("打印更新状态错误：未找到订单[" + ediOrder.getOrdeno() + "]对应的WorkOrder!");
			}
			/** end modify 20161018 bug:515 */
			
			// 保存订单日志
			OrderLog orderlog = new OrderLog(ediOrder.getOrdeno(), ediOrder.getCustomerCode(), "9", curUser, new Date(), null, new StringBuilder().append(curUser.getRealname()).append("已打印快递单据:").append(mailNo).append("(").append(logisticsCompanyCode).append(")").toString());

			orderLogDao.save(orderlog);

		}

		/** begin modified 20161014 bug:515 */
		// 修改作业任务的打印状态
		Long unprintedCount = workOrderDao.countUnprintedList(taskCode);
		
		if (unprintedCount.longValue() == 0l) {
    		Map<String, String> map = workTaskDao.findTaskPrintStatusByTaskCode(taskCode);
    		
    		String printStatus = map.get("printStatus");
    		String packformStatus = map.get("packformStatus");
    		String customerCode = map.get("customerCode");
    		String batchCode = map.get("batchCode");
		
			if (!"printed".equals(printStatus)) {
				Customers customers = customersDao.findByCustomerCode(customerCode);
				// 判断是否打印随箱单或者保修单
				if ("1".equals(customers.getPackStatus())) {
					// 设置任务状态未已打印
					if ("yes".equals(packformStatus)) {
						printStatus = "printed";
					}
				} else {
					printStatus = "printed";
				}

				// 作业日志
				WorkLog workLog = new WorkLog(batchCode, "11", "执行打印快递单据（" + taskCode + "）", new Date(), curUser);
				workLogDao.save(workLog);
			}
			
			 workTaskDao.updateExpressPrintStatus("yes", printStatus, taskCode);
		}
		/** end modified 20161014 bug:515 */
	}

	/**
	 * 获得打印快递单所需要的信息
	 * 
	 * @param shippedOrder
	 * @param index
	 * @return
	 * @throws UnsupportedEncodingException
	 * @throws Exception
	 */
	public CNPrinterModel getExpressStyleModel(EdiOrder ediOrder, ShiroUser user, ExpressStyle template) {
		// PrinterModel pm = new PrinterModel();
		CNPrinterModel pm = new CNPrinterModel();

		if (null != user) {
			pm.setOperator(user.username);
		}

		String ordeno = ediOrder.getOrdeno();
		Customers customers = customersService.findByCustomerCode(ediOrder.getCustomerCode());
		Consignor consignor = consignorService.findCustomersId(customers.getId());

		pm.setDestCode(ediOrder.getDestCode());// 目的地代码
		pm.setOriginCode(ediOrder.getOriginCode());// 原寄地代码
		pm.setToAddress(ediOrder.getAddres().replace("\"", " "));// 收件人详细地址
		pm.setToPhone(ediOrder.getTeleph());// 收件人固定电话号码
		pm.setToName(ediOrder.getRecena());// 收件人姓名
		pm.setToMobile(ediOrder.getMobile());// 收货人手机号码
		pm.setToProvince(ediOrder.getProvna());// 收件人省
		pm.setToCity(ediOrder.getCityna());// 收件人市
		pm.setToTowns(ediOrder.getDistna());// 收件人镇
		pm.setDestination(ediOrder.getProvna());// 目的地
		pm.setToZipcode(ediOrder.getPostco());// 收件人邮政编码

		pm.setWaybillNo(ediOrder.getMailNo());// 能容运单号
		pm.setOrdeno(ordeno);// 订单号
		pm.setPayTime(TimeUtil.getNowDateStringDD(ediOrder.getCrtime()));
		pm.setFromno(ediOrder.getFromno());// 来源单号
		pm.setCustomerOrdeno(ediOrder.getCustomerOrdeno());// 商家订单号

		pm.setPostFee(ediOrder.getPosfee() + "");// 邮费
		pm.setAllCost(ediOrder.getActuallyPaid() + "");// 总价
		pm.setNumber(ediOrder.getSkuQty() + "");// 数量//数量
		pm.setBunick(ediOrder.getBunick());// 会员昵称
		pm.setExpressNo(ediOrder.getMailNo());// 快递单号
		pm.setCompanyCode(ediOrder.getCacode());// 快递公司编码
		pm.setCompanyName(ediOrder.getCaname());// 快递公司名字
		pm.setShopName(ediOrder.getShopna());// //店铺名称
		pm.setBz(ediOrder.getRemark());// 备注
		pm.setBillProvideSiteName(ediOrder.getShmemo()); // 运单发放站点

		pm.setToDistCode(ediOrder.getToShortAddress());// 目的地大头笔信息

		
        if (template.getIsInsured().intValue() == 1) {
           //顺丰保价不固定
            ediOrder.setInsuranceAmt(ediOrder.getTotalAmount().doubleValue() * template.getInsuredPoint().doubleValue());
            pm.setOrderAmount(ediOrder.getTotalAmount());// 声明价值
        } else {
            ediOrder.setInsuranceAmt(0.0);
        }
		
        pm.setInsuredFee(ediOrder.getInsuranceAmt());//保价费用   bug613顺丰快递增加保价字段 by zhangweize 
		
		YTOShortAddress ytoShortAddress = ytoShortAddressDao.findShortAddress(ediOrder.getProvna(), ediOrder.getCityna(), ediOrder.getDistna(), ediOrder.getCacode());
		pm.setShortAddress(ytoShortAddress == null ? ediOrder.getCityna() : ytoShortAddress.getShortAddress());

		// 设置仓库地址
		WarehouseAddress warehouseAddress = warehouseAddressService.findByWarehouseCode(ediOrder.getWarehouseCode());
		StringBuilder stringBuilder = new StringBuilder();
		if (warehouseAddress != null) {
			pm.setWarehouseAddress(stringBuilder.append(warehouseAddress.getProvName()).append(warehouseAddress.getCityName()).append(warehouseAddress.getDistName()).append(warehouseAddress.getAddress()).toString());
			pm.setWarehouseContact(warehouseAddress.getContact());
			pm.setWarehouseMobile(warehouseAddress.getMobile());

			CustomerAreaGroup customerWarehouse = customerAreaGroupService.findByCustomerCodeAndAreaGroupCode(ediOrder.getCustomerCode(), ediOrder.getWarehouseCode());
			if (customerWarehouse != null) {
				if ("1".equals(customerWarehouse.getCainiaoAddressStatus())) {
					pm.setWarehouseAddress(consignor.getAddress());
					pm.setWarehouseContact(consignor.getName());
					pm.setWarehouseMobile(consignor.getMobile());
				}
			}
		}

		WorkOrder workOrder = workOrderService.loadByAnyOrderno(ordeno);
		if (workOrder != null) {
			WorkTask workTask = this.workTaskService.loadTaskByCode(ediOrder.getBackupTaskCode());
			pm.setTaskName(new StringBuilder().append(ediOrder.getBatchTaskCode()).append("_").append(ediOrder.getBackupTaskCode()).append("_").append(workTask.getOrderQty()).append("_").append(workOrder.getRankno()).append(workOrder.getPrintFlag() > 0 ? "_C" + (workOrder.getPrintFlag() + 1) : "").toString());
			pm.setRankno(workOrder.getRankno());
			pm.setStockInfo(workOrder.getStockInfo());

			if ("QRT".equals(workOrder.getExpressCompany())) {
				if ("广东省".equals(ediOrder.getProvna())) {
					String address = pub("http://42.121.1.163:8888/geohash/getWord", "province=" + ediOrder.getProvna() + "&city=" + ediOrder.getCityna() + "&district=" + ediOrder.getDistna() + "&street=" + ediOrder.getAddres());
					JSONObject json = JSONObject.fromObject(address);
					if (null != json && json.containsKey("data")) {
						JSONObject data = JSONObject.fromObject(json.getString("data"));
						String zyshortAddress = data.getString("word");
						pm.setZyshortAddress(zyshortAddress);
					}
				}
			}
		}

		try {
			List<EcCorePrintRegion> ecCorePrintRegions = ecCorePrintRegionService.findByAreaName(ediOrder.getCityna());
			if (ecCorePrintRegions.isEmpty()) {
				pm.setTitleName(ediOrder.getCityna());// 电子面单抬头
			} else if (ecCorePrintRegions.size() == 1) {
				pm.setTitleName(ecCorePrintRegions.get(0).getTitleName());
			} else {
				EcCorePrintRegion ecCorePrintRegion = ecCorePrintRegionService.findByAreaNameAndLayers(ediOrder.getProvna(), 1);
				if (ecCorePrintRegion == null) {
					pm.setTitleName(ediOrder.getCityna());
				} else {
					for (EcCorePrintRegion epr : ecCorePrintRegions) {
						if (epr.getFullName().indexOf(ediOrder.getProvna()) == 0) {
							pm.setTitleName(epr.getTitleName());
							break;
						} else {
							pm.setTitleName(ediOrder.getCityna());
						}
					}
				}
			}
		} catch (Exception e) {

		}

		if ("ZTO".equals(template.getLogisticsCompany().getCompanyCode())) {
			pm.setShortAddress(ediOrder.getToShortAddress());
			pm.setTitleName(ediOrder.getMessage());
		}
		// 订单明细
		List<EdiOrderItem> ediOrderItems = ediOrderItemService.findByCustomerCodeAndOrdeno(ediOrder.getCustomerCode(), ordeno);
		List<PackItems> packItems = new ArrayList<PackItems>();
		int orderItems = ediOrderItems.size() > 3 ? 3 : ediOrderItems.size();
		int tempTotol = 0;// 计算一个订单包含的商品总数
		StringBuilder sb = new StringBuilder();
		for (int j = 0; j < orderItems; j++) {
			EdiOrderItem ediOrderItem = ediOrderItems.get(j);
			PackItems packItem = new PackItems();
			packItem.setPrice(ediOrderItem.getPri() + "");// 商品单价
			packItem.setPay(ediOrderItem.getPay() + "");// 应付金额
			packItem.setDis(ediOrderItem.getDis() + "");// 折扣
			packItem.setAmo(ediOrderItem.getAmo() + "");// 实际金额
			packItem.setNumber(ediOrderItem.getQty() + "");// 商品数量
			tempTotol += ediOrderItem.getQty();
			packItem.setItemName(ediOrderItem.getNam());// 商品名称
			packItem.setPromotion(ediOrderItem.getPro() + "");// 优惠金额
			packItem.setFormat(ediOrderItem.getSiz());// 商品规格
			packItem.setSkuNumber(ediOrderItem.getSku());// //商品SKU
			packItem.setItemCode(ediOrderItem.getSku());// //商品编号
			packItem.setArticleNumber(ediOrderItem.getArticleNumber());// 商品货号
			packItems.add(packItem);
			sb.append(ediOrderItem.getSku()).append("(").append(ediOrderItem.getQty()).append(") | ");
		}
		if (ediOrderItems.size() > 3) {
			for (int j = 3; j < ediOrderItems.size(); j++) {
				EdiOrderItem ediOrderItem = ediOrderItems.get(j);
				tempTotol += ediOrderItem.getQty();
			}
			sb.append("......");
		}
		pm.setTotalSkuNumber(tempTotol + "");
		pm.setPackItems(packItems);
		pm.setProductName(sb.toString());

		String weight = "";
		String length = "";// 长度 cm
		String width = ""; // 宽 cm
		String height = "";// 高 cm
		if (workOrder != null) {
			float _weight = 0;
			for (EdiOrderItem item : ediOrderItems) {
				EdiGoodsSku ediGoodsSku = ediGoodsskuService.findByCustomerCodeAndSku(workOrder.getCustomerCode(), item.getSku());
				if (null == ediGoodsSku) {
					continue;
				}
				_weight += (ediGoodsSku.getWeight() == null ? 0 : ediGoodsSku.getWeight()) + (ediGoodsSku.getWeightPkg() == null ? 0 : ediGoodsSku.getWeightPkg());
				if ("single".equals(ediOrder.getOrderType()) && "MID".equals(workOrder.getCustomerCode())) {
					length = Float.parseFloat(ediGoodsSku.getLen()) / 10 + "cm";
					width = Float.parseFloat(ediGoodsSku.getWid()) / 10 + "cm";
					height = Float.parseFloat(ediGoodsSku.getHei()) / 10 + "cm";
				}
				if ("multiple".equals(ediOrder.getOrderType()) && "MID".equals(workOrder.getCustomerCode())) {
					if ("1".equals(ediGoodsSku.getSellFlg())) {
						length = Float.parseFloat(ediGoodsSku.getLen()) / 10 + "cm";
						width = Float.parseFloat(ediGoodsSku.getWid()) / 10 + "cm";
						height = Float.parseFloat(ediGoodsSku.getHei()) / 10 + "cm";
					}
				}
			}
			weight = _weight / 1000 + "kg";
			pm.setWeight(weight);
			pm.setLength(length);
			pm.setWidth(width);
			pm.setHeight(height);

		}
		// 寄件人信息
		if (consignor != null) {
			pm.setFromAddress(consignor.getAddress());
			pm.setFromName(consignor.getName());
			pm.setFromPhone(consignor.getPhone());
			pm.setFromMobile(consignor.getMobile());
			pm.setFromCompany(consignor.getAddress());
			pm.setOrigin(consignor.getDistrict());
			pm.setFromZipcode(consignor.getZipcode());
			pm.setFromCity(consignor.getCity());
			pm.setFromTowns(consignor.getDistrict());
		}

		// 菜鸟打印所需的字段
		if ("1".equals(template.getCainiaoFlg())) {
			// 设置菜鸟字段
			pm.setShortAddress(ediOrder.getToShortAddress());
			pm.setProductType(null);
			pm.setPackageCenterName(ediOrder.getPackageCenterName());
			pm.setPackageCenterCode(ediOrder.getPackageCenterCode());
			pm.setShippingBranchName(ediOrder.getShippingBranchName());
			pm.setShippingBranchCode(ediOrder.getShippingBranchCode());
			pm.setExtSFBizType(null);
			pm.setShippingAddressCity(null);
			pm.setPrintConfig(ediOrder.getPrintConfig());

			// 电话设置到一个字段内
			if (StringUtils.isBlank(pm.getToPhone())) {
				pm.setToPhone(pm.getToMobile());
			} else if (!StringUtils.isBlank(pm.getToMobile()) && !pm.getToPhone().equals(pm.getToMobile())) {
				pm.setToPhone(new StringBuilder().append(pm.getToPhone()).append("   ").append(pm.getToMobile()).toString());
			}
		}
		
		pm.setCustomSkuName(customers.getCustomerIntro());
		return pm;
	}

	/**
	 * 渲染快递模板
	 * 
	 *
	 * @param printerModel
	 * @param expressStyle
	 * @return [参数说明]
	 * @author <a href=mailto:zhangweize@nryuncang.com>zhangweize</a>
	 * @version 1.0.0
	 */
	private PrinterStyleType getPrinterStyleType(CNPrinterModel printerModel, ExpressStyle expressStyle) {
		String contentString = null;
		try {
			// PrinterStyleType printerStyleType = new PrinterStyleType();
			CNPrinterStyleType printerStyleType = new CNPrinterStyleType();
			if ("1".equals(expressStyle.getCainiaoFlg())) {
				printerStyleType.setContent(expressStyle.getStyleContent());
				printerStyleType.setCnPrinterModel(printerModel);
			} else {
				String expressContent = FileOperation.readerContent(expressStyle.getStyleContent());// 转化的时候
				if ("normal".equals(expressStyle.getType())) {
					contentString = PrintModelUtil.replaceParams(expressContent, printerModel);
				} else if ("mail".equals(expressStyle.getType())) {
					contentString = PackFormUtil.replaceParams(expressContent, printerModel);

				}
				contentString = contentString.replace("'", "\\'").replaceAll("\"", "'");
				printerStyleType.setContent(contentString);

			}
			printerStyleType.setCompanyCode(expressStyle.getLogisticsCompany().getCompanyCode());
			printerStyleType.setCompanyName(expressStyle.getLogisticsCompany().getCompanyName());
			printerStyleType.setTaskName(printerModel.getTaskName());
			printerStyleType.setRankno(printerModel.getRankno());
			printerStyleType.setOrdeno(printerModel.getOrdeno());
			printerStyleType.setTime(printerModel.getPayTime());
			printerStyleType.setFromno(printerModel.getFromno());
			printerStyleType.setExpressNo(printerModel.getExpressNo());
			printerStyleType.setCustomerCode(expressStyle.getCustomerCode());
			return printerStyleType;
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public String pub(String serviceURL, String param) {
		URL url = null;
		HttpURLConnection connection = null;
		StringBuffer buffer = new StringBuffer();
		try {
			url = new URL(serviceURL);
			connection = (HttpURLConnection) url.openConnection();
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setUseCaches(false);
			connection.setRequestMethod("POST");
			connection.setRequestProperty("Content-Length", param.length() + "");
			OutputStream os = connection.getOutputStream();
			DataOutputStream dos = new DataOutputStream(os);
			dos.write(param.getBytes("UTF-8"));
			dos.flush();
			dos.close();
			InputStream inputStream = connection.getInputStream();
			byte[] bytes = new byte[1024];
			int count = inputStream.read(bytes);
			while (count != -1) {
				buffer.append(new String(bytes, 0, count, "UTF-8"));
				count = inputStream.read(bytes);
			}
			inputStream.close();
		} catch (IOException e) {
			e.printStackTrace();

		} finally {
			if (connection != null) {
				connection.disconnect();
			}
		}
		return buffer.toString();
	}

}
